#include "Button_Handler.h"

uint8 u8button1_state;
uint8 u8button2_state;
uint8 u8button3_state;
uint8 u8button4_state;

void vfnButton_GPIO_Setup (void)
{
    BUTTON_GREEN_PULLUP = PULLUP_ENABLED;
    BUTTON_RED_PULLUP = PULLUP_ENABLED;           
    BUTTON_BLUE_PULLUP = PULLUP_ENABLED;
    BUTTON_YELLOW_PULLUP = PULLUP_ENABLED;
    
    BUTTON_GREEN_DD = GPIO_INPUT;
    BUTTON_RED_DD = GPIO_INPUT;
    BUTTON_BLUE_DD = GPIO_INPUT;
    BUTTON_YELLOW_DD = GPIO_INPUT; 
}

void vfnButton_StateInit (void)
{
    u8button1_state = BUTTON_STATE_FREE;
    u8button2_state = BUTTON_STATE_FREE;
    u8button3_state = BUTTON_STATE_FREE;
    u8button4_state = BUTTON_STATE_FREE;      
}

uint8 u8Button_Read (void)
{
    uint8 u8temp = 0;
    /* BUTTON 1 */ 
    
    if( (u8button1_state == BUTTON_STATE_FREE) && !BUTTON_GREEN ) // if button 1 was previously free
    {
        u8temp |= 0x01;
        u8button1_state = BUTTON_STATE_PRESSED;
    }
    else    // if button 1 was previously pressed 
    {
        
        if (BUTTON_GREEN)
        {
            // if button 1 was let go, then return to free state
            u8button1_state = BUTTON_STATE_FREE;    
        }
    }
    
    /* BUTTON 2 */
    
    if( (u8button2_state == BUTTON_STATE_FREE) && !BUTTON_RED ) // if button 2 was previously free
    {
        u8temp |= 0x02;
        u8button2_state = BUTTON_STATE_PRESSED;
    }
    else    // if button 2 was previously pressed 
    {
        
        if (BUTTON_RED)
        {
            // if button 2 was let go, then return to free state
            u8button2_state = BUTTON_STATE_FREE;    
        }
    }
    
    /* BUTTON 3 */
    
    if( (u8button3_state == BUTTON_STATE_FREE) && !BUTTON_BLUE ) // if button 3 was previously free
    {
        u8temp |= 0x04;
        u8button3_state = BUTTON_STATE_PRESSED;
    }
    else    // if button 3 was previously pressed 
    {
        
        if (BUTTON_BLUE)
        {
            // if button 3 was let go, then return to free state
            u8button3_state = BUTTON_STATE_FREE;    
        }
    }
    
    /* BUTTON 4 */
    
    if( (u8button4_state == BUTTON_STATE_FREE) && !BUTTON_YELLOW ) // if button 4 was previously free
    {
        u8temp |= 0x08;
        u8button4_state = BUTTON_STATE_PRESSED;
    }
    else    // if button 4 was previously pressed 
    {
        
        if (BUTTON_YELLOW)
        {
            // if button 4 was let go, then return to free state
            u8button4_state = BUTTON_STATE_FREE;    
        }
    }
    
    u8temp |= (u8button4_state << 7);
    u8temp |= (u8button3_state << 6);
    u8temp |= (u8button2_state << 5);
    u8temp |= (u8button1_state << 4);
    
    return u8temp;
}
